package com.futvan.z.framework.common.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.bean.Zfile;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.FileUtil;
import com.futvan.z.framework.util.ImgUtil;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.framework.util.SystemUtil;

import net.lingala.zip4j.ZipFile;

@Controller
public class FileCommonAction extends SuperAction{

	@Autowired
	protected HttpServletRequest request;



	/**
	 * 获取所有已上传文件信息
	 * @return
	 */
	private List<File> filelist;



	/**
	 * 启动页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/index")
	public String index() throws Exception {
		return "index";
	}

	/**
	 * 登录
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/UserLogin")
	public ModelAndView UserLogin(@RequestParam HashMap<String,String> bean) throws Exception {
		ModelAndView mv = new ModelAndView();
		String username = bean.get("username");
		String password = bean.get("password");
		if(isNotNull(username) && isNotNull(password)) {
			if(username.equals(sp.get("admin_username")) && password.equals(sp.get("admin_password"))) {
				//获取所有文件列表信息
				mv.addObject("filelist", GetFileList());
				mv.setViewName("main");
			}else {
				mv.setViewName("index");
				mv.addObject("info", "账号或密码错误");
			}
		}else {
			mv.setViewName("index");
			mv.addObject("info", "账号与密码不可为空");
		}
		return mv;
	}

	/**
	 * 打开文件上传页面
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/openUploadFile")
	public ModelAndView openUploadFile(@RequestParam HashMap<String,String> bean) throws Exception {
		ModelAndView model = new ModelAndView("file_upload");
		model.addObject("zid",newZid());
		return model;
	}



	/**
	 * 	上传文件【原文件名保存】
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public @ResponseBody Result upload(String filepath,String return_url_head,HttpServletRequest request){
		Result result = new Result();
		String fileReturnPath = "";
		List<String> uploadFileList = new ArrayList<String>();
		try {
			//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
			//检查form中是否有enctype="multipart/form-data"
			if(multipartResolver.isMultipart(request)){
				//将request变成多部分request
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

				//获取multiRequest 中所有的文件名
				Iterator iter=multiRequest.getFileNames();
				while(iter.hasNext()){
					//一次遍历所有文件
					MultipartFile file=multiRequest.getFile(iter.next().toString());
					if(file!=null){
						if(filepath==null || "".equals(filepath)) {
							filepath = SystemUtil.newNumber();
						}

						//创建保存路径
						String fileSavePath = CreateFileSavePath(filepath);

						//保存文件
						save(file,fileSavePath+"/"+file.getOriginalFilename(),true);

						if(return_url_head==null || "".equals(return_url_head)) {
							return_url_head = sp.get("url");
						}else {
							return_url_head = UrlDecode(return_url_head);
						}
						//创建返回URL
						fileReturnPath = return_url_head +"/files/"+filepath+"/"+file.getOriginalFilename();
						uploadFileList.add(fileReturnPath);

						//如果是图片，返回压缩图片路径
//						if(ImgUtil.isImg(file.getOriginalFilename())) {
//							String z1_fileReturnPath = return_url_head+"/files/"+filepath+"/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) +"_z1." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 
//							uploadFileList.add(z1_fileReturnPath);
//							String z5_fileReturnPath = return_url_head+"/files/"+filepath+"/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) +"_z5." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 
//							uploadFileList.add(z5_fileReturnPath);
//						}
					}
				}
			}
			result.setCode(Code.SUCCESS);
			result.setMsg(JsonUtil.listToJson(uploadFileList));
			result.setData(fileReturnPath);

		} catch (Exception e) {
			result.setCode(Code.ERROR);
			result.setMsg("file upload error："+e.getMessage());
			result.setData(e.getMessage());
		} 
		return result;
	}

	/**
	 * 	文件流上传 【生成新的文件名】
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/upload2",method=RequestMethod.POST)
	public @ResponseBody Result upload2(String return_url_head,HttpServletRequest request){
		Result result = new Result();
		String fileReturnPath = "";
		List<String> uploadFileList = new ArrayList<String>();
		try {
			//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
			//检查form中是否有enctype="multipart/form-data"
			if(multipartResolver.isMultipart(request)){
				//将request变成多部分request
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

				//获取multiRequest 中所有的文件名
				Iterator iter=multiRequest.getFileNames();
				while(iter.hasNext()){
					//一次遍历所有文件
					MultipartFile file=multiRequest.getFile(iter.next().toString());
					if(file!=null){

						//创建保存路径
						String fileSavePath = CreateFileSavePath("imgs");
						String ExtensionName = getExtensionName(file.getOriginalFilename());
						String filename = SystemUtil.newNumber()+ExtensionName;

						//保存文件
						save(file,fileSavePath+"/"+filename,true);

						//创建返回URL
						if(return_url_head==null || "".equals(return_url_head)) {
							return_url_head = sp.get("url");
						}else {
							return_url_head = UrlDecode(return_url_head);
						}
						fileReturnPath = return_url_head+"/files/"+filename;
						uploadFileList.add(fileReturnPath);

						//如果是图片，返回压缩图片路径
						if(ImgUtil.isImg(file.getOriginalFilename())) {
							String z1_fileReturnPath = return_url_head+"/files/"+ filename.substring(0, filename.lastIndexOf(".")) +"_z1." + filename.substring(filename.lastIndexOf(".")+1); 
							uploadFileList.add(z1_fileReturnPath);

							String z5_fileReturnPath = return_url_head+"/files/"+ filename.substring(0, filename.lastIndexOf(".")) +"_z5." + filename.substring(filename.lastIndexOf(".")+1); 
							uploadFileList.add(z5_fileReturnPath);
						}
					}
				}
			}
			result.setCode(Code.SUCCESS);
			result.setData(fileReturnPath);
			result.setMsg(JsonUtil.listToJson(uploadFileList));

		} catch (Exception e) {
			result.setCode(Code.ERROR);
			result.setMsg("file upload error："+e.getMessage());
			result.setData(e.getMessage());
		} 
		return result;
	}


	/**
	 * 	上传文件【原文件名保存】
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/upload_no_save_zip",method=RequestMethod.POST)
	public @ResponseBody Result upload_no_save_zip(String filepath,String return_url_head,HttpServletRequest request){
		Result result = new Result();
		String fileReturnPath = "";
		List<String> uploadFileList = new ArrayList<String>();
		try {
			//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
			//检查form中是否有enctype="multipart/form-data"
			if(multipartResolver.isMultipart(request)){
				//将request变成多部分request
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

				//获取multiRequest 中所有的文件名
				Iterator iter=multiRequest.getFileNames();
				while(iter.hasNext()){
					//一次遍历所有文件
					MultipartFile file=multiRequest.getFile(iter.next().toString());
					if(file!=null){
						if(filepath==null || "".equals(filepath)) {
							filepath = SystemUtil.newNumber();
						}

						//创建保存路径
						String fileSavePath = CreateFileSavePath(filepath);

						//保存文件
						save(file,fileSavePath+"/"+file.getOriginalFilename(),false);

						if(return_url_head==null || "".equals(return_url_head)) {
							return_url_head = sp.get("url");
						}else {
							return_url_head = UrlDecode(return_url_head);
						}
						//创建返回URL
						fileReturnPath = return_url_head +"/files/"+filepath+"/"+file.getOriginalFilename();
						uploadFileList.add(fileReturnPath);
					}
				}
			}
			result.setCode(Code.SUCCESS);
			result.setMsg(JsonUtil.listToJson(uploadFileList));
			result.setData(fileReturnPath);

		} catch (Exception e) {
			result.setCode(Code.ERROR);
			result.setMsg("file upload error："+e.getMessage());
			result.setData(e.getMessage());
		} 
		return result;
	}



	/**
	 * 	通过URL上传图片【上传文件会出错】
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/upload_imgurl",method=RequestMethod.POST)
	public @ResponseBody Result upload_imgurl(String file_url,String return_url_head){
		Result result = new Result();
		List<String> uploadFileList = new ArrayList<String>();
		if(!"".equals(file_url) && !"NULL".equals(file_url)&& !"Null".equals(file_url)&& !"null".equals(file_url) && file_url!=null) {
			try {
				//创建保存路径
				String fileSavePath = CreateFileSavePath("upload_imgurl");

				String filename = SystemUtil.newNumber();
				if(file_url.indexOf(".jpg")>=0){
					filename = filename + ".jpg";
				}else if(file_url.indexOf(".png")>=0) {
					filename = filename + ".png";
				}else if(file_url.indexOf(".jpeg")>=0) {
					filename = filename + ".jpeg";
				}else if(file_url.indexOf(".bmp")>=0) {
					filename = filename + ".bmp";
				}else if(file_url.indexOf(".gif")>=0) {
					filename = filename + ".gif";
				}else if(file_url.indexOf(".tiff")>=0) {
					filename = filename + ".tiff";
				}else if(file_url.indexOf(".raw")>=0) {
					filename = filename + ".raw";
				}else {
					filename = filename + ".jpg";
				}

				//创建连接
				URL url = new URL(file_url);
				InputStream is = url.openStream();
				//生成输出流
				OutputStream os = new FileOutputStream(fileSavePath+"/"+filename);
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while((bytesRead = is.read(buffer,0,8192))!=-1){
					os.write(buffer,0,bytesRead);
				}
				os.close();

				//同时生成压缩文件
				ImgUtil.ImgZip(fileSavePath+"/"+filename);

				//创建返回URL
				if(return_url_head==null || "".equals(return_url_head)) {
					return_url_head = sp.get("url");
				}else {
					return_url_head = UrlDecode(return_url_head);
				}
				//创建返回URL
				String fileReturnPath = return_url_head+"/files/"+filename;
				uploadFileList.add(fileReturnPath);

				//如果是图片，返回压缩图片路径
				if(ImgUtil.isImg(filename)) {
					String z1_fileReturnPath = return_url_head+"/files/"+ filename.substring(0, filename.lastIndexOf(".")) +"_z1." + filename.substring(filename.lastIndexOf(".")+1); 
					uploadFileList.add(z1_fileReturnPath);

					String z5_fileReturnPath = return_url_head+"/files/"+ filename.substring(0, filename.lastIndexOf(".")) +"_z5." + filename.substring(filename.lastIndexOf(".")+1); 
					uploadFileList.add(z5_fileReturnPath);
				}


				result.setCode(Code.SUCCESS);
				result.setMsg(JsonUtil.listToJson(uploadFileList));
				result.setData(fileReturnPath);

			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg("file upload error");
				result.setData(e.getMessage());
			} 
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("url is not null");
		}
		return result;
	}

	/**
	 * 获取文件信息
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/getFileInfo",method=RequestMethod.GET)
	public @ResponseBody Result getFileInfo(String filepath){
		Result result = new Result();
		String newfilepath = filepath;
		if(!"".equals(newfilepath) && newfilepath!=null) {
			if(newfilepath.substring(0,1).equals("/")) {
				newfilepath = newfilepath.substring(1);
			}
			newfilepath = request.getServletContext().getRealPath("/")+ newfilepath;

			//获取文件信息
			File f = new File(newfilepath);
			if(f.exists()) {
				HashMap<String,String> rMap = new HashMap<String,String>();
				//获取MD5
				rMap.put("md5", FileUtil.getFileMD5(newfilepath));
				//获取文件大小
				rMap.put("length", String.valueOf(f.length()));

				result.setCode(Code.SUCCESS);
				result.setMsg("ok");
				result.setData(rMap);
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未找到文件|"+filepath);
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("文件路径不可为空|filepath null");
		}
		return result;
	}

	/**
	 * 删除文件
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/deleteServerFile",method=RequestMethod.POST)
	public @ResponseBody Result deleteServerFile(@RequestParam HashMap<String,String> bean){
		Result result = new Result();
		String path = bean.get("path");
		String filename = bean.get("filename");
		if(isNotNull(path) && isNotNull(filename)) {
			String project_path = request.getServletContext().getRealPath("/")+"files\\";
			File f = new File(project_path+path+"\\"+filename);
			if (f.exists() && f.isFile()) {
				boolean b = f.delete();
				if(b) {
					//同时删除 z5 z1压缩版
					String[]filenameArray = filename.split("\\.");
					String fileName_z1 = filenameArray[0] +"_z1." + filenameArray[1];
					File f_z1 = new File(project_path+path+"\\"+fileName_z1);
					f_z1.delete();
					String fileName_z5 = filenameArray[0] +"_z5." + filenameArray[1];
					File f_z5 = new File(project_path+path+"\\"+fileName_z5);
					f_z5.delete();

					//删除成功后，判读文件夹是否为空，如果为空删文件夹
					String dirPath = project_path+path;
					if(FileUtil.dirsIsNull(dirPath)) {
						File dir = new File(dirPath);
						dir.delete();
					}

					result.setCode(Code.SUCCESS);
					result.setMsg("删除文件成功");
				}else{
					result.setCode(Code.ERROR);
					result.setMsg("删除文件失败|f.delete() return false");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未找到要删除的文件");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("path 和 filename 参数不可为空");
		}
		return result;
	}
	
	@RequestMapping(value="/upload_imgdate")
	public @ResponseBody Result upload_imgdate(@RequestParam HashMap<String,String> bean) throws Exception{
		Result result = new Result();
		String imgdate = bean.get("imgdate");
		String ColumnId = bean.get("ColumnId");
		String PageType = bean.get("PageType");
		String zid = bean.get("zid");
		String tableId = bean.get("tableId");
		
		if(isNotNull(tableId)){
			if(isNotNull(zid)){
				if(isNotNull(PageType)){
					if(isNotNull(ColumnId)){
						if(isNotNull(imgdate)){
							String name = SystemUtil.newNumber()+".jpg";
							
							//创建保存路径
							String fileSavePath = CreateFileSavePath("img");

							//转义还原
							imgdate = URLDecoder.decode(imgdate, "utf-8");
							
							//保存文件
							ImgUtil.Base64ToImg(fileSavePath+"/"+name,imgdate);
							
							//创建返回URL
							String fileReturnPath = sp.get("url") +fileSavePath.replace(System.getProperty("web.zf.root"), "")+"/"+name;
							
							result.setCode(Code.SUCCESS);
							result.setMsg("上传成功");
							result.setData(fileReturnPath);
						}else {
							result.setCode(Code.ERROR);
							result.setMsg("imgdate is null");
						}
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("ColumnId is null");
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("PageType is null");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("zid is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("tableId is null");
		}
		return result;
	}

	/**
	 * 删除文件
	 * @param zid
	 * @return
	 */
	@RequestMapping(value="/deleteFile",method=RequestMethod.GET)
	public @ResponseBody Result deleteFile(String zid){
		Result result = new Result();
		if(isNotNull(zid)) {
			String zfilepath = StringUtil.jie(zid).replace("☆", "\\");
			File file = new File(zfilepath);
			if(file.exists() && file.isFile()) {
				boolean isDelete = file.delete();
				if(isDelete) {
					result.setCode(Code.SUCCESS);
					result.setMsg("成功删除文件");
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("删除文件不成功");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未找到文件");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("zid is null");
		}
		return result;
	}


	/**
	 * 备份文件直接返回下载流
	 * @param name 压缩包文件名前缀
	 * @param path 本地目标地址
	 * @return 下载文件流
	 */
	@RequestMapping(value="/backup_file")
	public ResponseEntity<byte[]> backup_file(String name,String path){
		ResponseEntity<byte[]> result = null;
		if(isNotNull(path)) {
			try {
				String ZipFilePath = backupFile(name, path);
				if(isNotNull(ZipFilePath)) {
					File Zip = new File(ZipFilePath);
					long ontG = 1073741824;//标准1G
					if(Zip.length()<=ontG) {
						//压缩包转文件流
						byte[] file = FileUtil.getBytes(Zip);

						//创建文件头信息
						HttpHeaders headers = new HttpHeaders();
						String DirectoryName = path.substring(path.lastIndexOf("\\")+1);
						String ZipFileName = name+"_"+DirectoryName+"_"+DateUtil.getDateTime("yyyyMMddHHmm")+".zip";
						headers.setContentDispositionFormData("attachment", ZipFileName);
						headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
						
						//返回文件流
						result = new ResponseEntity<byte[]>(file,headers, HttpStatus.CREATED);
					}else {
						String error = "生成压缩文件大于1G，请使用backup_file_result，返回下载地址方式下载";
						result = new ResponseEntity<byte[]>(error.getBytes(),null, HttpStatus.CREATED);
					}
				}else {
					String error = "生成压缩文件出错，请联系管理员查看问题";
					result = new ResponseEntity<byte[]>(error.getBytes(),null, HttpStatus.CREATED);
				}
			} catch (IOException e) {
				String error = StringUtil.ExceptionToString(e);
				result = new ResponseEntity<byte[]>(error.getBytes(),null, HttpStatus.CREATED);
			}
		}else {
			String error = "备份目录不可为空";
			result = new ResponseEntity<byte[]>(error.getBytes(),null, HttpStatus.CREATED);
		}
		return result;
	}


	/**
	 * 备份文件返回下载地址
	 * @param name
	 * @param path
	 * @return
	 */
	@RequestMapping(value="/backup_file_result")
	public @ResponseBody Result backup_file_result(String name,String path){
		Result result = new Result();
		if(isNotNull(path)) {
			try {
				String ZipFilePath = backupFile(name, path);
				if(isNotNull(ZipFilePath)) {
					
					result.setCode(Code.SUCCESS);
					result.setData(sp.get("url")+"/temp_backup/"+new File(ZipFilePath).getName());
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("生成压缩文件出错");
				}
			} catch (IOException e) {
				result.setCode(Code.ERROR);
				result.setMsg(StringUtil.ExceptionToString(e));
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("备份目录不可为空");
		}
		return result;
	}

	private String backupFile(String name,String path) throws IOException {
		String ZipPath = "";
		//复制要备份的目录到位置
		File backPath = new File(path);
		if(backPath.exists() && backPath.isDirectory()) {
			//创建临时目录
			String tempPath = request.getServletContext().getRealPath("")+"\\temp_backup\\";
			//判读临时目录是否存在，如果有先执行清空操作
			if(new File(tempPath).exists() &&  new File(tempPath).isDirectory()) {
				FileUtil.deleteDir(new File(tempPath));
			}
			//创建临时目录
			FileUtil.mkdirs(tempPath);
			File tempPathFile = new File(tempPath);
			if(tempPathFile.exists() && tempPathFile.isDirectory()) {//判断临时目录是否创建成功
				//拷贝目录
				FileUtils.copyDirectoryToDirectory(backPath, tempPathFile);
	
				//压缩目录
				String DirectoryName = path.substring(path.lastIndexOf("\\")+1);
				String ZipFilePath = tempPath+name+"_"+DirectoryName+"_"+DateUtil.getDateTime("yyyyMMddHHmm")+".zip";
				new ZipFile(ZipFilePath).addFolder(new File(tempPath+DirectoryName));
	
				//判读压缩文件是否生成
				File ZipFile = new File(ZipFilePath);
				if(ZipFile.exists() && ZipFile.isFile()) {
					//删除拷贝的文件
					FileUtil.deleteDir(new File(tempPath+DirectoryName));
					ZipPath = ZipFile.getPath();
				}
			}
		}
		return ZipPath;
	}

	/**
	 * 获取文件扩展名
	 * @param originalFilename
	 * @return
	 */
	private String getExtensionName(String originalFilename) {
		String result = "";
		if(originalFilename!=null && !"".equals(originalFilename)) {
			int dot = originalFilename.lastIndexOf('.'); 
			if ((dot >-1) && (dot < (originalFilename.length() - 1))) { 
				result = originalFilename.substring(dot); 
			} 
		}
		return result;
	}

	/**
	 * 创建文件存储路径
	 * @param filepath
	 * @return
	 * @throws Exception
	 */
	private String CreateFileSavePath(String filepath) throws Exception{
		String fileSavePath = request.getServletContext().getRealPath("/")+"files/";
		if(isNotNull(filepath)) {
			fileSavePath = fileSavePath + filepath;
			// 判断文件目录是否存在如果不存在怎么创建
			File dir = new File(fileSavePath);
			if (!dir.exists() && !dir.isDirectory()) {
				//创建多级目录
				dir.mkdirs();
			}
		}else {
			throw new Exception("文件服务器系统错误:创建文件保存路径出错。请稍后上传。");
		}
		return fileSavePath;
	}

	/**
	 * 保存文件
	 * @throws Exception
	 */
	private void save(MultipartFile file,String fileSavePath,boolean isSaveZip) throws Exception{
		file.transferTo(new File(fileSavePath));
		if(isSaveZip) {
			//同时生成压缩文件
			ImgUtil.ImgZip(fileSavePath);
		}
	}

	/**
	 * 删除文件
	 * @param url 文件URL路径
	 * @param filename 
	 * @return 返回删除状态
	 */
	private Result DeleteFile(String file_path) {
		Result result = new Result();
		//获取目标和文件信息  结果：  XXXXXXXXXXXXXXXXXXXX/XXX.jpg
		String project_path = request.getServletContext().getRealPath("/");
		File f = new File(project_path + "files/" + file_path);
		if (f.exists() && f.isFile()) {
			boolean b = f.delete();
			if(b) {
				String [] pathArray = file_path.split("/");
				//同时删除 z5 z1压缩版
				String fileName_z1 = pathArray[1].substring(0, pathArray[1].lastIndexOf(".")) +"_z1." + pathArray[1].substring(pathArray[1].lastIndexOf(".")+1);
				File f_z1 = new File(project_path+"/files/"+pathArray[0]+"/"+fileName_z1);
				f_z1.delete();
				String fileName_z5 = pathArray[1].substring(0, pathArray[1].lastIndexOf(".")) +"_z5." + pathArray[1].substring(pathArray[1].lastIndexOf(".")+1);
				File f_z5 = new File(project_path+"/files/"+pathArray[0]+"/"+fileName_z5);
				f_z5.delete();

				//删除成功后，判读文件夹是否为空，如果为空删文件夹
				String dirPath = project_path+"/files/"+pathArray[0];
				if(FileUtil.dirsIsNull(dirPath)) {
					File dir = new File(dirPath);
					dir.delete();
				}

				result.setCode(Code.SUCCESS);
				result.setMsg("删除文件成功");
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("服务器中无法删除该文件");
			}
		}else {
			result.setCode(Code.SUCCESS);
			result.setMsg("服务器中未找到该文件");
		}
		return result;
	}

	private List<Zfile> GetFileList() {
		List<Zfile> fl = new ArrayList<Zfile>();
		File files_path = new File(request.getServletContext().getRealPath("/")+"files");
		filelist = new ArrayList<File>();
		//遍历文件目录，获取所有文件
		getDirAllFileList(files_path);
		filelist.sort(new Comparator<File>() {
			public int compare(File o1, File o2) {
				if(o1.lastModified()==o2.lastModified()) {
					return 0;
				}else if(o1.lastModified()>o2.lastModified()) {
					return -1;
				}else {
					return 1;
				}
			}
		});


		for (File f : filelist) {
			Zfile zf = new Zfile();
			zf.setZid(StringUtil.jia(f.getPath().replace("\\", "☆")));
			zf.setName(f.getName());
			//			zf.setType(type);
			String size = "";
			if(f.length()<=1048576) {
				size = String.valueOf(f.length()/1024)+"K";
			}else if(f.length()>1048576 && f.length()<=1073741824) {
				size = String.valueOf(f.length()/1024/1024)+"M";
			}else if(f.length()>1073741824){
				size = String.valueOf(f.length()/1024/1024/1024)+"G";
			}
			zf.setSize(size);
			zf.setCreate_time(DateUtil.FormatDate(new Date(f.lastModified()), "yyyy-MM-dd HH:mm:ss"));
			zf.setUrl(sp.get("url")+"/files"+f.getPath().replace(files_path.getPath(), "").replace("\\", "/"));
			fl.add(zf);
		}
		return fl;
	}

	private void getDirAllFileList(File dir) {
		if(dir.exists() && dir.isDirectory() && isNotNull(filelist)) {
			File[] files = dir.listFiles();
			for (File df : files) {
				if (df.isDirectory()) {
					getDirAllFileList(df);
				} else {
					filelist.add(df);
				}
			}
		}

	}

}
